import sys
import os
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
from PySide6.QtQuick import *
from PySide6.QtQuickWidgets import *
from PySide6.QtQml import *

class Demo(QWidget):
    
    def __init__(self, parent=None):
        super().__init__(parent)        
        self.parent = parent
        self.qml=os.path.join(self.parent.getAppDir(),'test.qml')
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        
        toolBar=QToolBar()
        btn=QPushButton('SaveFile')
        btn.clicked.connect(self.Save)
        toolBar.addWidget(btn)

        btn=QPushButton('ShowQuickWidget')
        btn.clicked.connect(self.ShowQuickWidget)
        toolBar.addWidget(btn)

        btn=QPushButton('ShowQuickView')
        btn.clicked.connect(self.ShowQuickView)
        toolBar.addWidget(btn)

        #btn=QPushButton('ShowQMLEngine')
        #btn.clicked.connect(self.ShowQMLEngine)
        #toolBar.addWidget(btn)
        layout.addWidget(toolBar)

        self.text=QTextEdit()
        layout.addWidget(self.text)

        self.setLayout(layout)
        #加载一次文件内容
        self.Load()        
    
    def Load(self):
        #textedit展示文档内容
        file=QFile(self.qml)
        file.open(QIODeviceBase.OpenModeFlag.ReadOnly)
        content=file.readAll()
        file.close()
        self.text.setPlainText(content.toStdString())
    def Save(self):
        content=self.text.toPlainText()
        file=QFile(self.qml)
        file.open(QIODeviceBase.OpenModeFlag.WriteOnly)
        file.write(QByteArray(content.encode()))
        file.close()
        self.parent.OnShowMessage(f'Save qml success: {self.qml}')
    def ShowQuickWidget(self):
        self.quickWidget=QQuickWidget()
        self.quickWidget.setWindowTitle('QQuickWidget Display QML')        
        self.quickWidget.setWindowModality(Qt.WindowModality.ApplicationModal)#设置模态窗口
        self.quickWidget.setSource(QUrl().fromLocalFile(self.qml))    
        if len(self.quickWidget.errors())>0:
            self.parent.OnShowMessage(f'qml has error,please check')
        else:
            self.quickWidget.show()
            self.parent.OnShowMessage(f'Show qml success: {self.qml}')
        
    def ShowQuickView(self):
        self.quickView=QQuickView()
        self.quickView.setTitle('QQuickView Display QML')        
        self.quickView.setModality(Qt.WindowModality.ApplicationModal)#设置模态窗口
        self.quickView.setSource(QUrl().fromLocalFile(self.qml))
        if len(self.quickView.errors())>0:
            self.parent.OnShowMessage(f'qml has error,please check')
        else:
            self.quickView.show()
            self.parent.OnShowMessage(f'Show qml success: {self.qml}')
    def ShowQMLEngine(self):
        self.engine=QQmlApplicationEngine()
        self.engine.load(QUrl().fromLocalFile(self.qml))        
        
def runDemo(parent):
    wigdet =  Demo(parent)
    return wigdet